#ifndef TELNET_H
#define TELNET_H

//#include <Server.h>
#include <Ethernet.h>

#include "domino.h"

extern char bname[6];

//! Telnet server instance
Server Telnet(23);

void initTelnetServer(){
	Telnet.begin();
}

/// This function reads the command from a telnet port
bool readFromTelnetPort(char *instruction)
{
	byte b;
	byte i=0;
	Client client = Telnet.available();
	if (client) {
  //Serial.println("RE");
		while (client.available() > 0) {
			b = client.read();
			switch (b) {
			case -1:	// Null char
			case 0:	// Null char
			case 33:	// !
			case 34:	// "
			case 35:	// #
			case 39:	// '
			case 10:	// LF: No deberia suceder, salvo en consola emulada
				break;
			case 4:	// EOT
			case 64:	// '@'
			case 127:	// DEL
//				Serial.print("N:telnq=");
//				Serial.println(b, DEC);
				client.stop();	// Close connection
				break;
			case 13:	// Final de linea
				output = TELNET;
				//processInstruction(instruction);
				i = 0;
				Serial.print("D:req=");
				Serial.println(instruction);
				return true;
				break;
			default:
				if ((i < BUFFERSIZE)
				    && (b >= 32 && b <= 126)) {
					instruction[i] = b;
					i++;
					instruction[i] = 0;
				} else {
					i = 0;
//					Serial.print(b, DEC);
				}
			}
		}
		//client.stop();
	}
	return false;
}

void sendOpenDomoAnnouncement(){
	char msg[50];
	char ipbuff[6];
	byte remoteip[4];
	remoteip[0]=eeprom_get_byte(EMNETCFOFFSET+7);
	remoteip[1]=eeprom_get_byte(EMNETCFOFFSET+8);
	remoteip[2]=eeprom_get_byte(EMNETCFOFFSET+9);
	remoteip[3]=255;


	strlcpy(msg, "OPENDOMO DEVICE ", sizeof(msg));
	itoan(remoteip[0],ipbuff,4); ipbuff[3]='.'; ipbuff[4]=0;
	strlcat(msg,ipbuff,sizeof(msg));
	itoan(remoteip[1],ipbuff,4); ipbuff[3]='.'; ipbuff[4]=0;
	strlcat(msg,ipbuff,sizeof(msg));
	itoan(remoteip[2],ipbuff,4); ipbuff[3]='.'; ipbuff[4]=0;
	strlcat(msg,ipbuff,sizeof(msg));
	itoan(eeprom_get_byte(EMNETCFOFFSET+10),ipbuff,4); ipbuff[3]=' '; ipbuff[4]=0;
	strlcat(msg,ipbuff,sizeof(msg));
	strlcat(msg,bname,sizeof(msg));
	Serial.println(msg);
	Udp.sendPacket(msg,remoteip,22537);
}

#endif
